/**
 * 
 */
package edu.cse5311.operations;

import edu.cse5311.constants.Constants;
import edu.cse5311.entity.Item;
import edu.cse5311.entity.LogBuffer;
import edu.cse5311.entity.LogDisk;
import edu.cse5311.entity.Operation;
import edu.cse5311.entity.Transaction;
import edu.cse5311.impl.Initialize;
import edu.cse5311.impl.Output;

/**
 * @author Karthik MG/ Shwetha Narayan
 * 
 * this class aids in the logging operations. Every transactional or system operation encountered
 * has to be logged in order to recover from any failure that might happen
 * 
 */
public class LogOperations {

	/**
	 * This method simulates the functions of writing the data into a Log Cache.
	 * The size of the log buffer is set to hold 4 buffers. Each buffer can hold
	 * the operation that was done in the Data buffer on an item and the
	 * transaction that did the operation.
	 * 
	 * @param item
	 * @param operation
	 * @param transaction
	 */
	public void updateLogBuffer(Item item, Operation operation,
			Transaction transaction) {

		// If all the buffers in the LOg Cache is full, flush the contents of
		// the Cache to Log Disk
		if (Initialize.logBufferList.size() == 4) {

			Output output = new Output();
			output.outputDetailsToFile(Constants.LOG_BUFFER_FULL);
			
			writeToLogDisk();

		}

		// Create a Log buffer object that holds all the details.
		LogBuffer logBuffer = new LogBuffer();
		logBuffer.setItem(item);
		logBuffer.setOperation(operation);
		logBuffer.setTransaction(transaction);
				// Add the buffer just created into the List, to simulate the
		// functionalities of a Log Cache(which can hold 4 operations).
		Initialize.logBufferList.add(logBuffer);

	}

	/**
	 * This method flushes all the details in the Log Buffer into the Log Disk.
	 */
	public void writeToLogDisk() {

		for (int i = 0; i < Initialize.logBufferList.size(); i++) {
			LogBuffer logBuffer = Initialize.logBufferList.get(i);

			LogDisk logDisk = new LogDisk();
			logDisk.setItem(logBuffer.getItem());
			logDisk.setOperation(logBuffer.getOperation());
			logDisk.setTransaction(logBuffer.getTransaction());
			
			Initialize.logDisk.add(logDisk);
		}
		
		Initialize.logBufferList.clear();
		
		Output output = new Output();
		output.outputDetailsToFile(Constants.LOG_DISK_WRITE);

	}

}
